<template>
    <u-tabbar :value="value" :placeholder="false" zIndex="9999" activeColor="#fe292b" :safeAreaInsetBottom="true">
        <u-tabbar-item
            v-for="(item, index) in list"
            :key="`k${index}`"
            :text="item.name"
            :name="index"
            @click="tabbarClick(item, index)">
            <template #active-icon>
                <image class="u-page__item__slot-icon" :src="item.imgurl[0]"></image>
            </template>
            <template #inactive-icon>
                <image class="u-page__item__slot-icon" :src="item.imgurl[1]"></image>
            </template>
        </u-tabbar-item>
    </u-tabbar>
</template>

<script setup>
import store from '@/store';
import storage from '@/commons/storage';
import { isNotEmpty } from '@/commons/utils';
import { computed } from 'vue';
import router from '@/router';

const props = defineProps({
    url: { type: String }
});
const useTabBarStore = store.useTabBarStore();
const list = computed(() => useTabBarStore.list);
const path = ['/pages/tabbar/home', '/pages/tabbar/category', '/pages/tabbar/cart', '/pages/tabbar/user'];
const value = computed(() => {
    // 当前高亮项索引
    const activeIndex = useTabBarStore.activeIndex;
    // 当前页面 url  === 当前下标项 url
    const activeUrl = list.value[activeIndex]?.url === props.url;
    return isNotEmpty(activeIndex) && activeUrl
        ? useTabBarStore.activeIndex
        : list.value.findIndex(item => item.url === props.url && item.mutual != 14);
});
const tabbarClick = (item, index) => {
    const url = item.url;
    // todo: 客服暂无 mutual ？
    // 多个相同tabbar页面切换 需记录索引来改变高亮按钮
    if (path.includes(url)) useTabBarStore.activeIndex = index;
    // 跳转到分类页面
    if (item.mutual == 4) {
        storage.set('CATEGORY_ID', item.id || '历史数据');
        // 【原因】如果tab之前已经打开，再跳转到tab页是不走任何生命周期的。
        // 【解决】通过getCurrentPages()方法获取当前打开的所有页，找到最后打开的页面（即：当前显示的页面），再调用onShow方法强制刷新！
        router.switchTab({
            url,
            success: function (e) {
                var page = getCurrentPages().pop();
                if (page == undefined || page == null) {
                    return;
                }
                page.onShow();
            }
        });
        // router.switchTab({ url, sucu });
    } else if (item.mutual === 14) {
        uni.navigateToMiniProgram({ appId: item.appId, path: url });
        // 打开图片
    } else if (item.mutual === 19) {
        uni.previewImage({ urls: [item.openimg], longPressActions: { itemList: ['发送给朋友', '保存图片', '收藏'] } });
    } else {
        // tabbar 页面切换
        if (path.includes(url)) {
            router.switchTab({ url });
            // 跳转到任意 非 tbabar 页面
        } else {
            router.push(url);
        }
    }
};
</script>

<style lang="scss" src="./index.scss" scoped></style>
